package pip.can;

import java.util.Random;

public class Zipf {

    private Random rnd;
    private int size;
    private double skew;
    private double bottom;

    public Zipf(int size, double skew) {
        this.rnd = new Random(System.currentTimeMillis());
        this.size = size;
        this.skew = skew;
        for (int i = 1; i <= size; i++) {
            this.bottom += (1.0d / Math.pow(i, this.skew));
        }
    }

    public int next(){
        int rank = -1;
        double frequency = 0.0d;
        double dice = 0.0d;
        while (dice >= frequency) {
            rank = this.rnd.nextInt(this.size);
            frequency = getProbability(rank + 1);
            dice = this.rnd.nextDouble();
        }
        return rank;
    }


    public double getProbability(int rank) {
        if (rank == 0) {
            throw new RuntimeException("getProbability - rank must be > 0");
        }
        return (1.0d / Math.pow(rank, this.skew)) / this.bottom;
    }



}

